<template>
  <div>
    <div>
      <a-modal
        v-model:visible="visible"
        title="上传图片"
        @ok="done"
        @cancel="visible = false"
      >
        <a-alert mb-10px>当前限制最多上传图片{{ props.limit || 1 }}张</a-alert>
        <div v-auto-animate>
          <a-upload
            v-if="visible"
            ref="uploadRef"
            image-preview
            :limit="props.limit || 1"
            list-type="picture"
            draggable
            :action="uploadFile"
            :headers="{ token: accessToken }"
            :onSuccess="success"
            :onError="handleError"
            @before-upload="beforeUpload"
          >
          </a-upload>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import uploadFile from '@/api/common';
  import {
    handleSuccess,
    handleError,
    beforeUpload,
    accessToken,
  } from '@/components/upload-pic/upload';

  const props = defineProps<{
    limit: number;
  }>();
  const url = ref<string>('');
  const emits = defineEmits<{ (e: 'onChange', fileUrl: string): void }>();
  const visible = ref<boolean>(false);
  function open() {
    visible.value = true;
  }
  function success(res: any) {
    url.value = handleSuccess(res);
  }
  function done() {
    emits('onChange', url.value);
  }
  defineExpose({ open });
</script>

<style lang="less" scoped></style>
